package com.atguigu.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.cart.fengin.ProductFengin;
import com.atguigu.cart.interceptor.CartInterceptor;
import com.atguigu.cart.service.CartService;
import com.atguigu.cart.vo.Cart;
import com.atguigu.cart.vo.CartItem;
import com.atguigu.cart.vo.SkuInfoVo;
import com.atguigu.cart.vo.UserInfoTo;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ProductFengin productFengin;
    @Resource
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> hashOps = getCartKey();

        //先查购物车有没有该商品
        String itemStr = (String)hashOps.get(skuId.toString());
        if(StringUtils.isEmpty(itemStr)){
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfo1 = CompletableFuture.runAsync(() -> {
                R info = productFengin.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);

            //远程调用用不同线程节省时间
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                cartItem.setSkuAttr(productFengin.getSkuAttrs(skuId));
            }, executor);

            CompletableFuture.allOf(skuInfo1, future).get();
            String s = JSON.toJSONString(cartItem);
            hashOps.put(skuId.toString(), s);
            return cartItem;
        }else{
            CartItem cartItem = JSON.parseObject(itemStr, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSON.toJSONString(cartItem);
            hashOps.put(skuId.toString(), s);
            return cartItem;
        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> hashOperations = getCartKey();
        Object item = hashOperations.get(skuId.toString());
        if(item != null){
            CartItem cartItem = JSON.parseObject(item.toString(), CartItem.class);
            return cartItem;
        }
        return null;
    }

    @Override
    public Cart getCarts() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.local.get();
        Cart cart = new Cart();
        if(userInfoTo.getUserId() != null  ){
            //已经登陆操作
            //当已经登陆时，把零时购物车的数据合并，并删除
            String tempKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempItems = getCartItems(tempKey);
            if(tempItems != null && tempItems.size() > 0){
                for (CartItem tempItem : tempItems) {
                    addToCart(tempItem.getSkuId(), tempItem.getCount());
                }
                clearCarts(tempKey);//清空零时购物车
            }

            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);

            cart.setItems(cartItems);
        }else {
            //未登陆操作
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }
        return cart;
    }

    @Override
    public void clearCarts(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public List<CartItem> getCheckItems() {
        UserInfoTo userInfoTo = CartInterceptor.local.get();
        if(userInfoTo.getUserId() != null){
            String tempKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(tempKey);
            cartItems = cartItems.stream().filter(cartItem -> cartItem.getCheck())
                    .map(cartItem -> {
                        //更新为最新价格
                        R price = productFengin.getPrice(cartItem.getSkuId());
                        String data = (String) price.get("data");
                        cartItem.setPrice(new BigDecimal(data));
                        return cartItem;
                    }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }

    private List<CartItem> getCartItems(String cartKey) {
        List<Object> values = stringRedisTemplate.boundHashOps(cartKey).values();
        if(values != null && values.size()>0){
            List<CartItem> collect = values.stream().map(obj -> {
                CartItem cartItem = JSON.parseObject(obj.toString(), CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartKey() {
        UserInfoTo userInfoTo = CartInterceptor.local.get();

        //拼接购物车的商品的key信息
        String cartKey = "";
        if(userInfoTo.getUserId() == null){
            //未登录处理
            cartKey += CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }else{
            //已登录处理
            cartKey += CartConstant.CART_PREFIX + userInfoTo.getUserId();
        }
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        return  hashOps;
    }
}
